"""
界面交互类 - 使用Pygame实现图形界面
"""

import pygame
import sys
import time
from core.board import Board
from core.game import Game, GameConfig
from ai.ai_player import AIPlayer
from account.score_system import ScoreSystem

class UI:
    def __init__(self, account_manager):
        # 初始化Pygame
        pygame.init()
        pygame.key.start_text_input()

        # 窗口设置
        self.WINDOW_WIDTH = 800
        self.WINDOW_HEIGHT = 800
        self.CELL_SIZE = 40
        self.BOARD_MARGIN = 50

        self.screen = pygame.display.set_mode((self.WINDOW_WIDTH, self.WINDOW_HEIGHT))
        pygame.display.set_caption("五子棋游戏")

        # 颜色定义
        self.BACKGROUND_COLOR = (220, 179, 92)  # 棋盘背景色
        self.LINE_COLOR = (0, 0, 0)  # 线条颜色
        self.BLACK_PIECE = (0, 0, 0)  # 黑棋
        self.WHITE_PIECE = (255, 255, 255)  # 白棋
        self.STAR_COLOR = (255, 0, 0)  # 星位颜色
        self.TEXT_COLOR = (0, 0, 0)  # 文字颜色

        # 游戏相关
        self.account_manager = account_manager
        self.current_game = None
        self.current_state = "LOGIN"  # LOGIN, REGISTER, MENU, GAME, GAME_OVER
        self.selected_difficulty = AIPlayer.Difficulty.MEDIUM
        self.message = ""
        self.message_time = 0

        # 字体
        self.font = pygame.font.SysFont('SimHei', 24)
        self.title_font = pygame.font.SysFont('SimHei', 36)
        self.small_font = pygame.font.SysFont('SimHei', 18)

        # UI配色
        self.PRIMARY_COLOR = (66, 115, 168)
        self.SECONDARY_COLOR = (238, 226, 207)
        self.ACCENT_COLOR = (244, 195, 109)
        self.NEUTRAL_DARK = (60, 60, 60)
        self.BUTTON_TEXT_COLOR = (40, 40, 40)

        # 渐变背景
        self.background_surface = pygame.Surface((self.WINDOW_WIDTH, self.WINDOW_HEIGHT))
        top_color = (250, 245, 235)
        bottom_color = (222, 204, 173)
        for y in range(self.WINDOW_HEIGHT):
            ratio = y / self.WINDOW_HEIGHT
            color = tuple(
                int(top_color[i] + (bottom_color[i] - top_color[i]) * ratio)
                for i in range(3)
            )
            pygame.draw.line(self.background_surface, color, (0, y), (self.WINDOW_WIDTH, y))

        # 通用按钮阴影偏移
        self.BUTTON_SHADOW_OFFSET = (3, 3)

        # 棋盘默认位置
        self.board_origin_x = self.BOARD_MARGIN
        self.board_origin_y = self.BOARD_MARGIN

        # 游戏控制按钮区域
        self.btn_width = 160
        self.btn_height = 40
        self.btn_undo_rect = pygame.Rect(600, 200, self.btn_width, self.btn_height)
        self.btn_pause_rect = pygame.Rect(600, 260, self.btn_width, self.btn_height)
        self.btn_restart_rect = pygame.Rect(600, 320, self.btn_width, self.btn_height)

        # 复盘相关
        self.replay_list = []  # 最近10局列表
        self.replay_steps = []  # 当前复盘步骤
        self.replay_index = 0   # 当前查看步数
        self.replay_board = Board(15)  # 复盘用棋盘

        # 登录注册输入状态
        self.login_inputs = {
            "account": "",
            "password": ""
        }
        self.register_inputs = {
            "account": "",
            "password": "",
            "nickname": ""
        }
        self.active_input = ("login", "account")

        # 管理面板状态
        self.admin_players = []  # 所有玩家列表
        self.input_boxes = {
            "login": {
                "account": pygame.Rect(300, 260, 200, 40),
                "password": pygame.Rect(300, 320, 200, 40)
            },
            "register": {
                "account": pygame.Rect(300, 240, 200, 40),
                "password": pygame.Rect(300, 300, 200, 40),
                "nickname": pygame.Rect(300, 360, 200, 40)
            }
        }

    # ===== UI辅助绘制函数 =====
    def draw_background(self):
        """绘制渐变背景和顶栏装饰"""
        self.screen.blit(self.background_surface, (0, 0))
        # 顶部装饰条
        overlay = pygame.Surface((self.WINDOW_WIDTH, 70), pygame.SRCALPHA)
        overlay.fill((255, 255, 255, 80))
        self.screen.blit(overlay, (0, 0))
        pygame.draw.line(self.screen, (210, 190, 150), (0, 70), (self.WINDOW_WIDTH, 70), 2)

    def draw_panel(self, rect, fill_color=None, border_color=None, border_radius=18, alpha=230):
        """绘制带圆角的面板"""
        fill_color = fill_color or self.SECONDARY_COLOR
        border_color = border_color or (200, 180, 150)
        panel_surface = pygame.Surface((rect.width, rect.height), pygame.SRCALPHA)
        fill_rgba = fill_color + (alpha,) if len(fill_color) == 3 else fill_color
        border_rgba = border_color + (alpha,) if len(border_color) == 3 else border_color
        pygame.draw.rect(panel_surface, fill_rgba, panel_surface.get_rect(), border_radius=border_radius)
        pygame.draw.rect(panel_surface, border_rgba, panel_surface.get_rect(),
                         width=2, border_radius=border_radius)
        self.screen.blit(panel_surface, rect.topleft)

    def draw_button(self, rect, text, bg_color=None, text_color=None, border_color=None, font=None):
        """绘制带阴影的按钮"""
        bg_color = bg_color or self.ACCENT_COLOR
        text_color = text_color or self.BUTTON_TEXT_COLOR
        border_color = border_color or (180, 160, 120)
        font = font or self.font

        # 阴影
        shadow_rect = rect.copy()
        shadow_rect.x += self.BUTTON_SHADOW_OFFSET[0]
        shadow_rect.y += self.BUTTON_SHADOW_OFFSET[1]
        shadow_surface = pygame.Surface((rect.width, rect.height), pygame.SRCALPHA)
        pygame.draw.rect(shadow_surface, (0, 0, 0, 70), shadow_surface.get_rect(), border_radius=14)
        self.screen.blit(shadow_surface, shadow_rect.topleft)

        # 主体
        pygame.draw.rect(self.screen, bg_color, rect, border_radius=14)
        pygame.draw.rect(self.screen, border_color, rect, width=2, border_radius=14)

        # 文本
        text_surface = font.render(text, True, text_color)
        text_pos = (rect.x + (rect.width - text_surface.get_width()) // 2,
                    rect.y + (rect.height - text_surface.get_height()) // 2)
        self.screen.blit(text_surface, text_pos)

    def draw_tag(self, pos, text, color=None):
        """绘制圆角标签"""
        color = color or self.PRIMARY_COLOR
        text_surface = self.small_font.render(text, True, (255, 255, 255))
        padding = 10
        rect = pygame.Rect(pos[0], pos[1], text_surface.get_width() + padding * 2,
                           text_surface.get_height() + padding)
        pygame.draw.rect(self.screen, color, rect, border_radius=12)
        text_pos = (rect.x + padding, rect.y + (rect.height - text_surface.get_height()) // 2)
        self.screen.blit(text_surface, text_pos)

    def run(self):
        """主循环"""
        clock = pygame.time.Clock()
        running = True

        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

                self.handle_event(event)

            # 回合计时与超时处理（游戏中）
            if self.current_state == "GAME" and self.current_game:
                # 检查是否超时并自动落子
                if self.current_game.check_and_handle_timeout():
                    if self.current_game.is_over():
                        self.handle_game_end()
                    else:
                        # 自动落子后轮到AI
                        self.show_message("AI思考中...")
                        pygame.display.flip()
                        time.sleep(0.3)
                        self.current_game.ai_place_piece()
                        if self.current_game.is_over():
                            self.handle_game_end()

            self.draw()
            pygame.display.flip()
            clock.tick(60)

        pygame.quit()
        sys.exit()

    def handle_event(self, event):
        """处理事件"""
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.current_state == "LOGIN":
                self.handle_login_click(event.pos)
            elif self.current_state == "REGISTER":
                self.handle_register_click(event.pos)
            elif self.current_state == "MENU":
                self.handle_menu_click(event.pos)
            elif self.current_state == "GAME":
                self.handle_game_click(event.pos)
            elif self.current_state == "GAME_OVER":
                self.handle_game_over_click(event.pos)
            elif self.current_state == "REPLAY_LIST":
                self.handle_replay_list_click(event.pos)
            elif self.current_state == "REPLAY_VIEW":
                self.handle_replay_view_click(event.pos)
            elif self.current_state == "ADMIN_PANEL":
                self.handle_admin_click(event.pos)
        elif event.type == pygame.KEYDOWN:
            self.handle_keydown(event)
        elif event.type == pygame.TEXTINPUT:
            self.handle_text_input(event)

    def handle_login_click(self, pos):
        """处理登录界面点击"""
        x, y = pos
        # 输入框点击
        for field, rect in self.input_boxes["login"].items():
            if rect.collidepoint(x, y):
                self.active_input = ("login", field)
                return

        # 登录按钮
        if 300 <= x <= 500 and 380 <= y <= 430:
            self.attempt_login()
            return

        # 跳转注册
        if 300 <= x <= 500 and 450 <= y <= 500:
            self.current_state = "REGISTER"
            self.active_input = ("register", "account")
            self.show_message("请输入注册信息")
            return

    def handle_register_click(self, pos):
        """处理注册界面点击"""
        x, y = pos
        for field, rect in self.input_boxes["register"].items():
            if rect.collidepoint(x, y):
                self.active_input = ("register", field)
                return

        # 注册按钮
        if 300 <= x <= 500 and 420 <= y <= 470:
            self.attempt_register()
            return

        # 返回登录
        if 300 <= x <= 500 and 490 <= y <= 540:
            self.current_state = "LOGIN"
            self.active_input = ("login", "account")
            self.show_message("已返回登录")
            return

    def handle_keydown(self, event):
        """处理键盘功能键（Tab/回车/删除）"""
        if self.current_state not in ("LOGIN", "REGISTER") or not self.active_input:
            return

        state, field = self.active_input
        if state == "login":
            fields_order = ["account", "password"]
            target = self.login_inputs
        else:
            fields_order = ["account", "password", "nickname"]
            target = self.register_inputs

        if event.key == pygame.K_TAB:
            idx = fields_order.index(field)
            idx = (idx + 1) % len(fields_order)
            self.active_input = (state, fields_order[idx])
            return

        if event.key == pygame.K_RETURN:
            if state == "login":
                self.attempt_login()
            else:
                self.attempt_register()
            return

        if event.key == pygame.K_BACKSPACE:
            target[field] = target[field][:-1]
            return

    def handle_text_input(self, event):
        """处理文本输入字符"""
        if self.current_state not in ("LOGIN", "REGISTER") or not self.active_input:
            return

        state, field = self.active_input
        if state == "login":
            target = self.login_inputs
        else:
            target = self.register_inputs

        text = getattr(event, "text", "")
        if not text:
            return

        if len(target[field]) + len(text) <= 30:
            target[field] += text

    def attempt_login(self):
        account = self.login_inputs["account"].strip()
        password = self.login_inputs["password"]

        if not account or not password:
            self.show_message("请输入账号和密码")
            return

        success, message = self.account_manager.login(account, password)
        if success:
            self.current_state = "MENU"
            self.show_message(message)
            self.login_inputs["password"] = ""
            self.active_input = None
        else:
            self.show_message(message)
            self.active_input = ("login", "account")

    def attempt_register(self):
        account = self.register_inputs["account"].strip()
        password = self.register_inputs["password"]
        nickname = self.register_inputs["nickname"].strip()

        if not account or not password or not nickname:
            self.show_message("请填写完整注册信息")
            if not account:
                self.active_input = ("register", "account")
            elif not password:
                self.active_input = ("register", "password")
            else:
                self.active_input = ("register", "nickname")
            return

        success, message = self.account_manager.register(account, password, nickname)
        if success:
            self.show_message("注册成功，请登录")
            self.login_inputs["account"] = account
            self.login_inputs["password"] = ""
            self.current_state = "LOGIN"
            self.active_input = ("login", "account")
        else:
            self.show_message(message)
            self.active_input = ("register", "account")

    def handle_menu_click(self, pos):
        """处理主菜单点击"""
        x, y = pos

        # 开始游戏按钮
        if 300 <= x <= 500 and 200 <= y <= 250:
            self.start_new_game()
            return

        # 退出按钮
        if 300 <= x <= 500 and 480 <= y <= 530:
            self.current_state = "LOGIN"
            self.account_manager.logout()
            self.active_input = ("login", "account")
            self.login_inputs["password"] = ""
            return

        # 难度选择按钮
        if 300 <= x <= 500:
            if 270 <= y <= 320:
                self.selected_difficulty = AIPlayer.Difficulty.EASY
                self.show_message("已选择简单难度")
            elif 340 <= y <= 390:
                self.selected_difficulty = AIPlayer.Difficulty.MEDIUM
                self.show_message("已选择中等难度")
            elif 410 <= y <= 460:
                self.selected_difficulty = AIPlayer.Difficulty.HARD
                self.show_message("已选择困难难度")

        # 退出按钮
        # 复盘按钮
        if 520 <= x <= 720 and 200 <= y <= 250:
            self.enter_replay_list()

        # 管理员面板按钮（仅管理员）
        user = self.account_manager.get_current_user()
        if user and self.account_manager.is_admin(user.account_id):
            if 520 <= x <= 720 and 270 <= y <= 320:
                self.enter_admin_panel()

    def handle_game_click(self, pos):
        """处理游戏界面点击"""
        if not self.current_game:
            return

        x, y = pos
        # 按钮点击：悔棋
        if self.btn_undo_rect.collidepoint(x, y):
            if self.current_game.undo():
                self.show_message("已悔棋两步")
            else:
                self.show_message("无法悔棋")
            return

        # 按钮点击：暂停/继续
        if self.btn_pause_rect.collidepoint(x, y):
            if not self.current_game.is_paused:
                if self.current_game.pause():
                    self.show_message("游戏已暂停")
            else:
                if self.current_game.resume():
                    self.show_message("继续游戏")
            return

        # 按钮点击：重新开始
        if self.btn_restart_rect.collidepoint(x, y):
            self.current_game.restart()
            self.show_message("已重新开始，黑棋先行")
            return

        # 棋盘点击：仅在人类回合且未暂停
        if self.current_game.current_turn == 1 and not self.current_game.is_paused:  # 人类回合
            grid_x, grid_y = self.screen_to_grid(pos[0], pos[1])
            if grid_x is not None and grid_y is not None:
                success = self.current_game.human_place_piece(grid_x, grid_y)
                if success:
                    # 检查游戏是否结束
                    if self.current_game.is_over():
                        self.handle_game_end()
                    else:
                        # AI回合
                        self.show_message("AI思考中...")
                        pygame.display.flip()
                        time.sleep(0.5)  # 给AI思考时间
                        self.current_game.ai_place_piece()
                        if self.current_game.is_over():
                            self.handle_game_end()

    def handle_game_over_click(self, pos):
        """处理游戏结束界面点击"""
        x, y = pos

        # 重新开始按钮
        if 300 <= x <= 500 and 350 <= y <= 400:
            self.start_new_game()

        # 返回菜单按钮
        elif 300 <= x <= 500 and 420 <= y <= 470:
            self.current_state = "MENU"

    def start_new_game(self):
        """开始新游戏"""
        from account.player import Player

        # 创建AI玩家
        ai_player = AIPlayer(self.selected_difficulty)

        # 创建游戏
        config = GameConfig(ai_difficulty=self.selected_difficulty, board_size=15, human_color=1, ai_color=2, time_limit=15)
        self.current_game = Game(self.account_manager.get_current_user(), ai_player, self.account_manager, config)
        self.current_game.start()

        self.current_state = "GAME"
        self.show_message("游戏开始！黑棋先行")

    def handle_game_end(self):
        """处理游戏结束"""
        self.current_state = "GAME_OVER"

        # 更新积分
        score_system = ScoreSystem()
        human_player = self.account_manager.get_current_user()

        if self.current_game.winner == 1:  # 人类获胜
            score_change = score_system.calculate_win(human_player, self.selected_difficulty)
            self.show_message(f"恭喜获胜！积分+{score_change}")
        elif self.current_game.winner == 2:  # AI获胜
            score_change = score_system.calculate_lose(human_player)
            self.show_message(f"很遗憾失败，积分{score_change}")
        else:  # 平局
            score_change = score_system.calculate_draw(human_player)
            self.show_message(f"平局！积分+{score_change}")

        # 保存玩家数据
        self.account_manager.update_player_info(human_player)

        # 保存完整复盘存档（含步骤）
        try:
            from storage.game_data import GameData
            gd = GameData()
            gd.from_game(self.current_game, human_player.account_id)
            self.account_manager.storage.save_game_data(gd)
        except Exception as e:
            print(f"保存复盘存档失败: {e}")

    def screen_to_grid(self, screen_x, screen_y):
        """屏幕坐标转换为棋盘坐标"""
        origin_x = getattr(self, "board_origin_x", self.BOARD_MARGIN)
        origin_y = getattr(self, "board_origin_y", self.BOARD_MARGIN)
        board_x = screen_x - origin_x
        board_y = screen_y - origin_y

        # 允许在交叉点周围一定范围内点击，使用最近的网格点
        half_cell = self.CELL_SIZE / 2
        max_coord = (self.current_game.board.SIZE - 1) * self.CELL_SIZE if self.current_game else (15 - 1) * self.CELL_SIZE

        if (board_x < -half_cell or board_y < -half_cell or
                board_x > max_coord + half_cell or board_y > max_coord + half_cell):
            return None, None

        grid_x = int(round(board_x / self.CELL_SIZE))
        grid_y = int(round(board_y / self.CELL_SIZE))

        if self.current_game:
            size = self.current_game.board.SIZE
        else:
            size = 15

        if grid_x < 0 or grid_x >= size or grid_y < 0 or grid_y >= size:
            grid_x = max(0, min(size - 1, grid_x))
            grid_y = max(0, min(size - 1, grid_y))

        return grid_x, grid_y

    def show_message(self, message, duration=2000):
        """显示消息"""
        self.message = message
        self.message_time = pygame.time.get_ticks() + duration

    def draw(self):
        """绘制界面"""
        self.draw_background()

        if self.current_state == "LOGIN":
            self.draw_login_ui()
        elif self.current_state == "REGISTER":
            self.draw_register_ui()
        elif self.current_state == "MENU":
            self.draw_menu_ui()
        elif self.current_state == "GAME":
            self.draw_game_ui()
        elif self.current_state == "GAME_OVER":
            self.draw_game_over_ui()
        elif self.current_state == "REPLAY_LIST":
            self.draw_replay_list_ui()
        elif self.current_state == "REPLAY_VIEW":
            self.draw_replay_view_ui()
        elif self.current_state == "ADMIN_PANEL":
            self.draw_admin_panel_ui()

        # 绘制消息
        if pygame.time.get_ticks() < self.message_time:
            text_surface = self.font.render(self.message, True, (170, 60, 50))
            width = max(text_surface.get_width() + 40, 220)
            height = 44
            message_surface = pygame.Surface((width, height), pygame.SRCALPHA)
            pygame.draw.rect(message_surface, (255, 255, 255, 230), message_surface.get_rect(), border_radius=16)
            pygame.draw.rect(message_surface, (200, 160, 120, 230), message_surface.get_rect(), width=2, border_radius=16)
            padding_x = (width - text_surface.get_width()) // 2
            padding_y = (height - text_surface.get_height()) // 2
            message_surface.blit(text_surface, (padding_x, padding_y))
            msg_rect = message_surface.get_rect()
            msg_rect.center = (self.WINDOW_WIDTH // 2, 35)
            self.screen.blit(message_surface, msg_rect.topleft)

    def draw_login_ui(self):
        """绘制登录界面"""
        title = self.title_font.render("五子棋游戏 - 登录", True, self.TEXT_COLOR)
        self.screen.blit(title, (self.WINDOW_WIDTH // 2 - title.get_width() // 2, 100))

        panel_rect = pygame.Rect(180, 150, 440, 320)
        self.draw_panel(panel_rect, fill_color=(245, 240, 230), border_radius=24)

        hint = self.font.render("请输入账号和密码登录", True, self.NEUTRAL_DARK)
        self.screen.blit(hint, (self.WINDOW_WIDTH // 2 - hint.get_width() // 2, 180))

        labels = {"account": "账号", "password": "密码"}
        for field, rect in self.input_boxes["login"].items():
            label = self.font.render(labels[field], True, self.TEXT_COLOR)
            self.screen.blit(label, (rect.x - 90, rect.y + (rect.height - label.get_height()) // 2))
            color = (100, 200, 100) if self.active_input == ("login", field) else (200, 200, 200)
            pygame.draw.rect(self.screen, (255, 255, 255), rect, border_radius=14)
            pygame.draw.rect(self.screen, color, rect, 2, border_radius=14)
            value = self.login_inputs[field]
            if field == "password":
                display_value = "*" * len(value)
            else:
                display_value = value
            text_surface = self.font.render(display_value, True, self.TEXT_COLOR)
            self.screen.blit(
                text_surface,
                (rect.x + (rect.width - text_surface.get_width()) // 2,
                 rect.y + (rect.height - text_surface.get_height()) // 2)
            )

        # 登录按钮
        self.draw_button(pygame.Rect(300, 380, 200, 50), "登录", self.PRIMARY_COLOR, text_color=(255, 255, 255))

        # 注册按钮
        self.draw_button(pygame.Rect(300, 450, 200, 50), "注册新账号", self.ACCENT_COLOR)

    def draw_register_ui(self):
        """绘制注册界面"""
        title = self.title_font.render("五子棋游戏 - 注册", True, self.TEXT_COLOR)
        self.screen.blit(title, (self.WINDOW_WIDTH // 2 - title.get_width() // 2, 100))

        panel_rect = pygame.Rect(180, 150, 440, 360)
        self.draw_panel(panel_rect, fill_color=(245, 240, 230), border_radius=24)

        hint = self.font.render("请输入账号、密码和昵称", True, self.NEUTRAL_DARK)
        self.screen.blit(hint, (self.WINDOW_WIDTH // 2 - hint.get_width() // 2, 180))

        labels = {"account": "账号", "password": "密码", "nickname": "昵称"}
        for field, rect in self.input_boxes["register"].items():
            label = self.font.render(labels[field], True, self.TEXT_COLOR)
            self.screen.blit(label, (rect.x - 90, rect.y + (rect.height - label.get_height()) // 2))
            color = (100, 200, 100) if self.active_input == ("register", field) else (200, 200, 200)
            pygame.draw.rect(self.screen, (255, 255, 255), rect, border_radius=14)
            pygame.draw.rect(self.screen, color, rect, 2, border_radius=14)
            value = self.register_inputs[field]
            if field == "password":
                display_value = "*" * len(value)
            else:
                display_value = value
            text_surface = self.font.render(display_value, True, self.TEXT_COLOR)
            self.screen.blit(
                text_surface,
                (rect.x + (rect.width - text_surface.get_width()) // 2,
                 rect.y + (rect.height - text_surface.get_height()) // 2)
            )

        # 注册按钮
        self.draw_button(pygame.Rect(300, 420, 200, 50), "完成注册", self.PRIMARY_COLOR, text_color=(255, 255, 255))

        # 返回登录
        self.draw_button(pygame.Rect(300, 490, 200, 50), "返回登录", (206, 112, 104), text_color=(255, 255, 255))

    def draw_menu_ui(self):
        """绘制主菜单界面"""
        title = self.title_font.render("五子棋游戏", True, self.TEXT_COLOR)
        self.screen.blit(title, (self.WINDOW_WIDTH // 2 - title.get_width() // 2, 100))

        # 显示当前用户信息
        user = self.account_manager.get_current_user()
        if user:
            user_text = self.font.render(f"欢迎，{user.nickname}！积分：{user.score}", True, self.TEXT_COLOR)
            self.screen.blit(user_text, (self.WINDOW_WIDTH // 2 - user_text.get_width() // 2, 150))
            # 展示统计数据
            stats = self.account_manager.get_player_stats()
            if stats:
                stats_lines = [
                    f"总局：{stats['total']}",
                    f"胜：{stats['win']}",
                    f"负：{stats['lose']}",
                    f"平：{stats['draw']}",
                    f"胜率：{int(stats['win_rate']*100)}%"
                ]
                stats_start_y = 200
                for i, line in enumerate(stats_lines):
                    badge_rect = pygame.Rect(120, stats_start_y + i * 50, 140, 40)
                    pygame.draw.rect(self.screen, (66, 115, 168), badge_rect, border_radius=16)
                    line_surface = self.font.render(line, True, (255, 255, 255))
                    self.screen.blit(
                        line_surface,
                        (badge_rect.x + (badge_rect.width - line_surface.get_width()) // 2,
                         badge_rect.y + (badge_rect.height - line_surface.get_height()) // 2)
                    )

        # 开始游戏按钮
        self.draw_button(pygame.Rect(300, 200, 200, 50), "开始游戏", self.PRIMARY_COLOR, text_color=(255, 255, 255))

        # 复盘按钮
        self.draw_button(pygame.Rect(560, 220, 160, 44), "复盘（近10局）", self.ACCENT_COLOR)

        # 管理员面板按钮（仅管理员显示）
        if user and self.account_manager.is_admin(user.account_id):
            self.draw_button(pygame.Rect(560, 270, 160, 44), "管理面板", (214, 112, 112), text_color=(255, 255, 255))

        # 难度选择
        diff_text = self.font.render("选择难度：", True, self.TEXT_COLOR)
        self.screen.blit(diff_text, (300, 270))

        difficulties = [
            ("简单", AIPlayer.Difficulty.EASY, 270),
            ("中等", AIPlayer.Difficulty.MEDIUM, 340),
            ("困难", AIPlayer.Difficulty.HARD, 410)
        ]

        for diff_name, diff_value, y_pos in difficulties:
            is_selected = self.selected_difficulty == diff_value
            color = self.PRIMARY_COLOR if is_selected else (210, 210, 210)
            text_color = (255, 255, 255) if is_selected else self.NEUTRAL_DARK
            self.draw_button(pygame.Rect(300, y_pos, 200, 50), diff_name, color, text_color=text_color)

        # 退出按钮
        self.draw_button(pygame.Rect(300, 480, 200, 50), "退出登录", (198, 78, 65), text_color=(255, 255, 255))

    def draw_game_ui(self):
        """绘制游戏界面"""
        if not self.current_game:
            return

        board_width = self.current_game.board.SIZE * self.CELL_SIZE
        self.board_origin_x = max(40, (self.WINDOW_WIDTH - board_width) // 2 - 80)
        self.board_origin_y = (self.WINDOW_HEIGHT - board_width) // 2

        # 绘制棋盘
        self.draw_board(self.current_game.board)

        # 显示游戏状态
        status_text = "黑棋回合" if self.current_game.current_turn == 1 else "白棋回合"
        if self.current_game.is_over():
            if self.current_game.winner == 1:
                status_text = "黑棋获胜！"
            elif self.current_game.winner == 2:
                status_text = "白棋获胜！"
            else:
                status_text = "平局！"

        status_surface = pygame.Surface((260, 50), pygame.SRCALPHA)
        pygame.draw.rect(status_surface, (255, 255, 255, 220), status_surface.get_rect(), border_radius=16)
        pygame.draw.rect(status_surface, (200, 180, 150, 220), status_surface.get_rect(), width=2, border_radius=16)
        text_surface = self.font.render(status_text, True, self.NEUTRAL_DARK)
        status_surface.blit(
            text_surface,
            ((status_surface.get_width() - text_surface.get_width()) // 2,
             (status_surface.get_height() - text_surface.get_height()) // 2)
        )
        self.screen.blit(status_surface, (40, 110))

        # 显示当前用户信息
        user = self.account_manager.get_current_user()
        if user:
            user_text = self.font.render(f"{user.nickname} 积分：{user.score}", True, self.TEXT_COLOR)
            info_surface = pygame.Surface((user_text.get_width() + 40, 44), pygame.SRCALPHA)
            pygame.draw.rect(info_surface, (255, 255, 255, 220), info_surface.get_rect(), border_radius=14)
            pygame.draw.rect(info_surface, (200, 180, 150, 220), info_surface.get_rect(), width=2, border_radius=14)
            info_surface.blit(user_text, (20, (44 - user_text.get_height()) // 2))
            self.screen.blit(info_surface, (self.WINDOW_WIDTH - info_surface.get_width() - 40, 20))

        # 控制面板背景
        control_panel = pygame.Rect(560, 140, 210, 260)
        self.draw_panel(control_panel)

        # 绘制控制按钮：悔棋、暂停/继续
        self.draw_button(self.btn_undo_rect, "悔棋（两步）", self.PRIMARY_COLOR, text_color=(255, 255, 255))

        pause_label = "暂停" if not self.current_game.is_paused else "继续"
        pause_color = (220, 180, 120) if not self.current_game.is_paused else (120, 180, 140)
        self.draw_button(self.btn_pause_rect, pause_label, pause_color)

        # 重新开始按钮
        self.draw_button(self.btn_restart_rect, "重新开始", (120, 200, 150))

        # 显示倒计时（仅在人类回合且未暂停）
        remaining = self.current_game.get_remaining_time()
        if remaining is not None:
            seconds = int(remaining + 0.999)
            timer_text = self.font.render(f"倒计时：{seconds}s / 15s", True, (200, 0, 0) if seconds <= 5 else self.TEXT_COLOR)
            timer_panel = pygame.Surface((timer_text.get_width() + 40, 44), pygame.SRCALPHA)
            pygame.draw.rect(timer_panel, (255, 255, 255, 220), timer_panel.get_rect(), border_radius=14)
            pygame.draw.rect(timer_panel, (200, 180, 150, 220), timer_panel.get_rect(), width=2, border_radius=14)
            timer_panel.blit(timer_text, (20, (44 - timer_text.get_height()) // 2))
            self.screen.blit(timer_panel, (40, 40))

    def draw_game_over_ui(self):
        """绘制游戏结束界面"""
        self.draw_game_ui()

        # 绘制半透明覆盖层
        overlay = pygame.Surface((self.WINDOW_WIDTH, self.WINDOW_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 128))
        self.screen.blit(overlay, (0, 0))

        # 显示结果
        if self.current_game.winner == 1:
            result_text = "恭喜你获胜！"
        elif self.current_game.winner == 2:
            result_text = "AI获胜！"
        else:
            result_text = "平局！"

        panel_rect = pygame.Rect(220, 240, 360, 260)
        self.draw_panel(panel_rect, fill_color=(255, 255, 255), border_color=(220, 180, 120))
        text_surface = self.title_font.render(result_text, True, self.NEUTRAL_DARK)
        self.screen.blit(text_surface, (self.WINDOW_WIDTH // 2 - text_surface.get_width() // 2, 270))

        # 重新开始按钮
        self.draw_button(pygame.Rect(300, 350, 200, 50), "重新开始", self.PRIMARY_COLOR, text_color=(255, 255, 255))

        # 返回菜单按钮
        self.draw_button(pygame.Rect(300, 420, 200, 50), "返回菜单", (198, 78, 65), text_color=(255, 255, 255))

    # ===== 复盘相关 =====
    def enter_replay_list(self):
        """进入复盘列表，查询最近10局"""
        user = self.account_manager.get_current_user()
        if not user:
            self.show_message("请先登录")
            return
        self.replay_list = self.account_manager.storage.get_saved_games(user.account_id, 10)
        self.current_state = "REPLAY_LIST"

    def handle_replay_list_click(self, pos):
        x, y = pos
        # 返回菜单
        if 50 <= x <= 200 and 40 <= y <= 80:
            self.current_state = "MENU"
            return
        # 列表项点击，每项高度50，从y=200开始
        start_y = 200
        if 100 <= x <= 700 and y >= start_y:
            idx = (y - start_y) // 50
            if 0 <= idx < len(self.replay_list):
                game_data = self.account_manager.storage.load_game_data(self.replay_list[idx].game_id)
                if game_data:
                    self.load_replay(game_data.history)
                    self.current_state = "REPLAY_VIEW"

    def load_replay(self, steps):
        """载入复盘数据"""
        self.replay_steps = steps or []
        self.replay_index = 0
        self.replay_board.init()

    def handle_replay_view_click(self, pos):
        x, y = pos
        # 返回列表
        if 50 <= x <= 200 and 40 <= y <= 80:
            self.current_state = "REPLAY_LIST"
            return
        # 跳到开始
        if 120 <= x <= 220 and 700 <= y <= 740:
            self.replay_jump(0)
            return
        # 上一手
        if 250 <= x <= 350 and 700 <= y <= 740:
            self.replay_step(-1)
            return
        # 下一手
        if 450 <= x <= 550 and 700 <= y <= 740:
            self.replay_step(1)
            return
        # 跳到结束
        if 580 <= x <= 680 and 700 <= y <= 740:
            self.replay_jump(len(self.replay_steps))
            return

    def replay_step(self, delta):
        """步进复盘"""
        new_index = max(0, min(len(self.replay_steps), self.replay_index + delta))
        if new_index == self.replay_index:
            return
        # 重新渲染至 new_index
        self.replay_board.init()
        for i in range(new_index):
            s = self.replay_steps[i]
            self.replay_board.set_piece(s.x, s.y, s.color)
        self.replay_index = new_index

    def replay_jump(self, index):
        index = max(0, min(len(self.replay_steps), index))
        self.replay_board.init()
        for i in range(index):
            s = self.replay_steps[i]
            self.replay_board.set_piece(s.x, s.y, s.color)
        self.replay_index = index

    def draw_replay_list_ui(self):
        """绘制复盘列表"""
        title = self.title_font.render("最近10局对局（复盘）", True, self.TEXT_COLOR)
        self.screen.blit(title, (self.WINDOW_WIDTH // 2 - title.get_width() // 2, 100))

        # 返回按钮
        self.draw_button(pygame.Rect(50, 40, 150, 40), "返回菜单", (198, 78, 65), text_color=(255, 255, 255))

        panel_rect = pygame.Rect(150, 160, 500, 500)
        self.draw_panel(panel_rect, fill_color=(245, 240, 230), border_radius=24)
        # 列表
        start_y = 200
        for i, gd in enumerate(self.replay_list):
            y = start_y + i * 50
            item_rect = pygame.Rect(180, y, 440, 50)
            pygame.draw.rect(self.screen, (245, 240, 230), item_rect, border_radius=10)
            pygame.draw.rect(self.screen, (210, 185, 150), item_rect, width=1, border_radius=10)
            info = f"{gd.create_time}  难度:{gd.ai_difficulty}  状态:{'完成' if gd.is_completed else '进行中'}"
            text = self.font.render(info, True, self.TEXT_COLOR)
            self.screen.blit(
                text,
                (item_rect.x + (item_rect.width - text.get_width()) // 2,
                 item_rect.y + (item_rect.height - text.get_height()) // 2)
            )

    def draw_replay_view_ui(self):
        """绘制复盘查看界面"""
        # 棋盘
        self.draw_board(self.replay_board)

        # 标题
        title = self.title_font.render("复盘查看", True, self.TEXT_COLOR)
        self.screen.blit(title, (self.WINDOW_WIDTH // 2 - title.get_width() // 2, 40))

        # 返回按钮
        self.draw_button(pygame.Rect(50, 40, 150, 40), "返回列表", (198, 78, 65), text_color=(255, 255, 255))

        # 控制条
        control_rect = pygame.Rect(100, 690, 600, 60)
        self.draw_panel(control_rect, fill_color=(252, 246, 236), border_color=(210, 185, 150), border_radius=14)
        # 跳到开始
        self.draw_button(pygame.Rect(120, 700, 100, 40), "<<", (180, 180, 240))
        # 上一手
        self.draw_button(pygame.Rect(250, 700, 100, 40), "<", (180, 240, 180))
        # 下一手
        self.draw_button(pygame.Rect(450, 700, 100, 40), ">", (180, 240, 180))
        # 跳到结束
        self.draw_button(pygame.Rect(580, 700, 100, 40), ">>", (180, 180, 240))

        # 步数信息
        step_info = self.font.render(f"步数：{self.replay_index}/{len(self.replay_steps)}", True, self.TEXT_COLOR)
        self.screen.blit(step_info, (320, 650))

    # ===== 管理面板 =====
    def enter_admin_panel(self):
        if not self.account_manager.is_admin(self.account_manager.get_current_user().account_id):
            self.show_message("无管理员权限")
            return
        self.admin_players = self.account_manager.get_all_players()
        self.current_state = "ADMIN_PANEL"

    def draw_admin_panel_ui(self):
        title = self.title_font.render("管理面板 - 所有玩家", True, self.TEXT_COLOR)
        self.screen.blit(title, (self.WINDOW_WIDTH // 2 - title.get_width() // 2, 100))

        # 返回菜单按钮
        self.draw_button(pygame.Rect(50, 40, 150, 40), "返回菜单", (198, 78, 65), text_color=(255, 255, 255))

        # 表头
        panel_rect = pygame.Rect(100, 150, 640, 480)
        self.draw_panel(panel_rect, fill_color=(245, 240, 230), border_radius=24)
        header_labels = ["账号ID", "昵称", "积分", "胜/负/平"]
        col_widths = [180, 160, 100, 180]
        col_positions = [140, 140 + col_widths[0], 140 + col_widths[0] + col_widths[1],
                         140 + col_widths[0] + col_widths[1] + col_widths[2]]
        for idx, label in enumerate(header_labels):
            header_surface = self.font.render(label, True, self.TEXT_COLOR)
            self.screen.blit(header_surface, (col_positions[idx], 180))

        # 列表
        start_y = 210
        col_positions = [140, 140 + col_widths[0], 140 + col_widths[0] + col_widths[1],
                         140 + col_widths[0] + col_widths[1] + col_widths[2]]
        for i, p in enumerate(self.admin_players):
            y = start_y + i * 40
            item_rect = pygame.Rect(120, y, 560, 44)
            pygame.draw.rect(self.screen, (245, 240, 230), item_rect, border_radius=10)
            pygame.draw.rect(self.screen, (210, 185, 150), item_rect, width=1, border_radius=10)
            fields = [
                p['account_id'],
                p['nickname'],
                str(p['score']),
                f"{p['win_count']}/{p['lose_count']}/{p['draw_count']}"
            ]
            for idx, text in enumerate(fields):
                field_surface = self.font.render(text, True, self.TEXT_COLOR)
                self.screen.blit(field_surface, (col_positions[idx], y + 10))
            # 删除按钮（不能删除自己）
            me = self.account_manager.get_current_user()
            if me and p['account_id'] != me.account_id:
                delete_rect = pygame.Rect(660, y, 90, 44)
                self.draw_button(delete_rect, "删除", (214, 112, 112), text_color=(255, 255, 255), font=self.small_font)

    def handle_admin_click(self, pos):
        x, y = pos
        # 返回菜单
        if 50 <= x <= 200 and 40 <= y <= 80:
            self.current_state = "MENU"
            return

        start_y = 210
        if 660 <= x <= 750 and y >= start_y:
            idx = (y - start_y) // 40
            if 0 <= idx < len(self.admin_players):
                target_id = self.admin_players[idx]['account_id']
                me = self.account_manager.get_current_user()
                if me and target_id == me.account_id:
                    self.show_message("不能删除自己")
                    return
                success, msg = self.account_manager.delete_player_account(target_id)
                self.show_message(msg)
                # 刷新列表
                self.admin_players = self.account_manager.get_all_players()
    def draw_board(self, board):
        """绘制棋盘"""
        # 绘制背景
        board_width = board.SIZE * self.CELL_SIZE
        origin_x = getattr(self, "board_origin_x", self.BOARD_MARGIN)
        origin_y = getattr(self, "board_origin_y", self.BOARD_MARGIN)
        board_rect = pygame.Rect(
            origin_x - 18,
            origin_y - 18,
            board_width + 36,
            board_width + 36
        )
        self.draw_panel(board_rect, fill_color=(240, 224, 195), border_color=(190, 160, 120))
        pygame.draw.rect(self.screen, self.BACKGROUND_COLOR,
                         (origin_x, origin_y, board_width, board_width))

        # 绘制网格线
        for i in range(board.SIZE):
            # 横线
            pygame.draw.line(self.screen, self.LINE_COLOR,
                             (origin_x, origin_y + i * self.CELL_SIZE),
                             (origin_x + board_width, origin_y + i * self.CELL_SIZE), 2)
            # 竖线
            pygame.draw.line(self.screen, self.LINE_COLOR,
                             (origin_x + i * self.CELL_SIZE, origin_y),
                             (origin_x + i * self.CELL_SIZE, origin_y + board_width), 2)

        # 绘制星位
        star_radius = 4
        for x, y in board.star_points:
            pygame.draw.circle(self.screen, self.STAR_COLOR,
                               (origin_x + x * self.CELL_SIZE,
                                origin_y + y * self.CELL_SIZE),
                               star_radius)

        # 绘制棋子
        for x in range(board.SIZE):
            for y in range(board.SIZE):
                piece = board.get_piece(x, y)
                if piece != 0:  # 有棋子
                    self.draw_piece(x, y, piece)


    def draw_piece(self, x, y, color):
        """绘制棋子"""
        origin_x = getattr(self, "board_origin_x", self.BOARD_MARGIN)
        origin_y = getattr(self, "board_origin_y", self.BOARD_MARGIN)
        center_x = origin_x + x * self.CELL_SIZE
        center_y = origin_y + y * self.CELL_SIZE
        radius = self.CELL_SIZE // 2 - 2

        if color == 1:  # 黑棋
            pygame.draw.circle(self.screen, self.BLACK_PIECE, (center_x, center_y), radius)
            # 添加高光效果
            pygame.draw.circle(self.screen, (100, 100, 100),
                               (center_x - radius // 3, center_y - radius // 3), radius // 4)
        else:  # 白棋
            pygame.draw.circle(self.screen, self.WHITE_PIECE, (center_x, center_y), radius)
            pygame.draw.circle(self.screen, (200, 200, 200), (center_x, center_y), radius, 1)
            # 添加高光效果
            pygame.draw.circle(self.screen, (240, 240, 240),
                               (center_x - radius // 3, center_y - radius // 3), radius // 4)

    def draw_coordinates(self):
        """绘制坐标标记"""
        # 绘制横坐标（字母）
        letters = "ABCDEFGHIJKLMNO"
        for i in range(15):
            text = self.font.render(letters[i], True, self.TEXT_COLOR)
            x = self.BOARD_MARGIN + i * self.CELL_SIZE - text.get_width() // 2
            y = self.BOARD_MARGIN - 25
            self.screen.blit(text, (x, y))

        # 绘制纵坐标（数字）
        for i in range(15):
            text = self.font.render(str(i + 1), True, self.TEXT_COLOR)
            x = self.BOARD_MARGIN - 25
            y = self.BOARD_MARGIN + i * self.CELL_SIZE - text.get_height() // 2
            self.screen.blit(text, (x, y))
